package com.happy.gateway.filter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * @Auther: lifeng
 * @Date: 2018/12/7 15:51
 * @Description:前置浏览器
 */
@Component
public class PreZuulFilter extends ZuulFilter {
  private static Logger log = LoggerFactory.getLogger(PreZuulFilter.class);
  @Override
  public String filterType() {
    return PRE_TYPE;
  }

  @Override
  public int filterOrder() {
    return PRE_DECORATION_FILTER_ORDER-5; //过滤器执行顺序，数字越小，优先级越高，越靠前,这里设置为 0
  }

  @Override
  public boolean shouldFilter() {
    return true; //这里边可以定义拦截条件
  }

  @Override
  public Object run() throws ZuulException {
   RequestContext requestContext =  RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    log.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
     String token = request.getParameter("token");
     if(StringUtils.isEmpty(token)){
      log.warn("token is empty");
      requestContext.setSendZuulResponse(false);
      requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
      return null;
     }
     log.info("token is ok");
    return null;
  }
}
